<template>
  <div class="doc-sidebar">
    <div class="doc-sidebar-header">
      <h3>文档资料</h3>
      <div class="header-actions">
        <el-tag type="info" v-if="currentAgentId" class="agent-tag">当前智能体: {{ currentAgentId }}</el-tag>
        <el-button type="text" @click="closeDocSidebar" class="close-btn">
          <el-icon><Close /></el-icon>
        </el-button>
      </div>
    </div>
    
    <div v-if="isLoading" class="doc-sidebar-loading">
      <el-skeleton :rows="10" animated />
    </div>
    
    <div v-else-if="docData" class="doc-sidebar-content">
      <h2 class="doc-title">{{ docData.name }}</h2>
      <p class="doc-description" v-if="docData.description">{{ docData.description }}</p>
      
      <!-- 参数信息 -->
      <div v-if="hasParams" class="doc-section">
        <h3 class="section-title">参数信息</h3>
        <div class="params-list">
          <div v-for="(value, key) in docData.params" :key="key" class="param-item">
            <div class="param-key">{{ key }}</div>
            <div class="param-value">{{ value }}</div>
          </div>
        </div>
      </div>
      
      <!-- 文档内容区块 -->
      <template v-if="documentBlocks && documentBlocks.length > 0">
        <div v-for="(block, index) in documentBlocks" :key="index" class="doc-block">
          <div :class="`block-title block-title-${block.type}`">{{ block.title }}</div>
          <div class="block-content">{{ block.content }}</div>
        </div>
      </template>
      
      <!-- 图片展示 -->
      <div v-if="imageBlocks && imageBlocks.length > 0" class="doc-images">
        <h3 class="section-title">相关图片</h3>
        <div class="image-grid">
          <div v-for="(img, index) in imageBlocks" :key="index" class="image-item">
            <el-image :src="img.url" :alt="img.name" fit="cover" :preview-src-list="imageUrls" />
            <p class="image-name">{{ img.name }}</p>
          </div>
        </div>
      </div>
    </div>
    
    <div v-else class="doc-sidebar-empty">
      <el-empty description="暂无文档数据" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, nextTick, onMounted, watch } from 'vue';
import { ElMessage } from 'element-plus';
import universalDocService, { ConfigItem } from '@/services/universalDocService';
import { Close } from '@element-plus/icons-vue';
import store from '@/store';

// 定义接口
interface DocumentBlock {
  type: string;
  title: string;
  content: string;
  rows: number;
  createdAt: number;
}

interface ParameterBlock {
  key: string;
  value: string;
  createdAt: number;
}

interface ImageBlock {
  url: string;
  name: string;
  createdAt: number;
}

// 状态
const currentAgentId = ref<string | null>(null);
const docData = ref<ConfigItem | null>(null);
const isLoading = ref<boolean>(false);
const documentBlocks = ref<DocumentBlock[]>([]);
const parameterBlocks = ref<ParameterBlock[]>([]);
const imageBlocks = ref<ImageBlock[]>([]);

// 计算属性
const hasParams = computed(() => {
  return docData.value && docData.value.params && Object.keys(docData.value.params).length > 0;
});

const imageUrls = computed(() => {
  return imageBlocks.value.map(img => img.url);
});

// 解析文档内容
const parseDocContent = (doc: ConfigItem) => {
  try {
    if (doc.content) {
      const contentObj = JSON.parse(doc.content);
      documentBlocks.value = contentObj.documents || [];
      parameterBlocks.value = contentObj.parameters || [];
      imageBlocks.value = contentObj.images || [];
    } else {
      documentBlocks.value = [];
      parameterBlocks.value = [];
      imageBlocks.value = [];
    }
  } catch (error) {
    console.error('解析文档内容失败:', error);
    documentBlocks.value = [];
    parameterBlocks.value = [];
    imageBlocks.value = [];
  }
};

// 加载与智能体关联的文档
const loadDocForAgent = async (agentId: string) => {
  isLoading.value = true;
  
  try {
    // 获取所有配置文档
    const configList = await universalDocService.getConfigList();
    
    // 查找匹配当前智能体ID的文档
    const matchedDoc = configList.find(doc => 
      doc.agent_ids && doc.agent_ids.includes(agentId)
    );
    
    if (matchedDoc) {
      docData.value = matchedDoc;
      parseDocContent(matchedDoc);
    } else {
      // 如果没有匹配的文档，加载默认文档
      console.log(`未找到与智能体ID "${agentId}" 关联的文档，加载默认文档`);
      await loadDefaultDoc();
    }
  } catch (error) {
    console.error('加载文档失败:', error);
    ElMessage.error('加载文档失败');
    // 出错时尝试加载默认文档
    await loadDefaultDoc().catch(e => {
      console.error('加载默认文档失败:', e);
      docData.value = null;
    });
  } finally {
    isLoading.value = false;
  }
};

// 加载默认文档（ID为1）
const loadDefaultDoc = async () => {
  isLoading.value = true;
  
  try {
    const configList = await universalDocService.getConfigList();
    const defaultDoc = configList.find(doc => doc.id === '1');
    
    if (defaultDoc) {
      docData.value = defaultDoc;
      parseDocContent(defaultDoc);
      console.log('已加载默认文档:', defaultDoc.name);
    } else {
      docData.value = null;
      documentBlocks.value = [];
      parameterBlocks.value = [];
      imageBlocks.value = [];
      console.log('未找到默认文档');
    }
  } catch (error) {
    console.error('加载默认文档失败:', error);
    ElMessage.error('加载默认文档失败');
    docData.value = null;
  } finally {
    isLoading.value = false;
  }
};

// 添加关闭侧边栏的方法
const closeDocSidebar = () => {
  try {
    if (store && typeof store.dispatch === 'function') {
      store.dispatch('hideRightSidebar');
    } else {
      console.error('store不可用或dispatch方法不存在');
      ElMessage.error('关闭侧边栏失败，请手动关闭');
    }
  } catch (error) {
    console.error('关闭侧边栏失败:', error);
    ElMessage.error('关闭侧边栏失败，请手动关闭');
  }
};

// 组件加载时执行
onMounted(async () => {
  try {
    // 延迟加载，确保组件完全挂载
    await nextTick();
    
    // 如果store初始化成功，设置监听
    if (store) {
      // 监听选中的智能体ID变化
      watch(() => {
        try {
          return store.state.selectedAgentIds;
        } catch (error) {
          console.error('获取selectedAgentIds失败:', error);
          return [];
        }
      }, (newIds) => {
        try {
          if (newIds && newIds.length > 0) {
            const newAgentId = newIds[0];
            currentAgentId.value = newAgentId;
            loadDocForAgent(newAgentId);
            console.log('智能体ID已更新:', newAgentId);
          } else {
            console.log('未选择智能体，加载默认文档');
            // 当没有选择智能体时，加载默认文档
            loadDefaultDoc();
          }
        } catch (error) {
          console.error('处理智能体ID变更失败:', error);
          // 出错时加载默认文档
          loadDefaultDoc();
        }
      }, { immediate: true, deep: true });
    } else {
      // 如果store不可用，加载默认文档
      console.log('Vuex store不可用，加载默认文档');
      await loadDefaultDoc();
    }
  } catch (error) {
    console.error('组件挂载出错:', error);
    await loadDefaultDoc();
  }
});
</script>

<style scoped>
.doc-sidebar {
  height: 100%;
  padding: 15px;
  display: flex;
  flex-direction: column;
}

.doc-sidebar-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e8e8e8;
}

.doc-sidebar-header h3 {
  margin: 0;
  font-size: 18px;
  color: #333;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.agent-tag {
  font-size: 12px;
}

.close-btn {
  padding: 2px;
  font-size: 16px;
  color: #909399;
  transition: color 0.2s;
}

.close-btn:hover {
  color: #409EFF;
}

.doc-sidebar-content {
  flex: 1;
  overflow-y: auto;
}

.doc-title {
  font-size: 20px;
  margin-top: 0;
  margin-bottom: 10px;
  color: #303133;
}

.doc-description {
  color: #606266;
  margin-bottom: 20px;
  font-size: 14px;
}

.doc-section {
  margin-bottom: 20px;
  background: #f9f9f9;
  border-radius: 8px;
  padding: 15px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  margin-top: 0;
  margin-bottom: 15px;
  color: #303133;
}

.doc-block {
  margin-bottom: 20px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.block-title {
  padding: 10px 15px;
  font-weight: 600;
  font-size: 15px;
}

.block-title-h1 {
  background: #e6f7ff;
  color: #1890ff;
}

.block-title-h2 {
  background: #f6ffed;
  color: #52c41a;
}

.block-title-h3 {
  background: #fff7e6;
  color: #fa8c16;
}

.block-title-h4 {
  background: #fff1f0;
  color: #f5222d;
}

.block-content {
  padding: 15px;
  line-height: 1.6;
  background: white;
  word-break: break-word;
  white-space: pre-wrap;
}

.doc-images {
  margin-top: 20px;
}

.image-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
  gap: 15px;
}

.image-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.image-item .el-image {
  width: 100%;
  height: 120px;
  border-radius: 4px;
}

.image-name {
  margin-top: 8px;
  font-size: 12px;
  text-align: center;
  color: #606266;
}

.doc-sidebar-loading,
.doc-sidebar-empty {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}

.params-list {
  margin-top: 10px;
}

.param-item {
  display: flex;
  margin-bottom: 8px;
  padding: 8px;
  border-bottom: 1px solid #eee;
}

.param-key {
  font-weight: bold;
  min-width: 120px;
  color: #606266;
}

.param-value {
  flex: 1;
  color: #333;
}
</style> 